/*
 * 文件名：Client.java
 * 描述： Client.java
 * 修改人：Lo&Wang
 * 修改时间：2016年11月24日
 * 修改内容：新增
 */
package com.lowang.test.netty;

import com.lowang.test.netty.handler.HelloWorldClientHandler;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.serialization.ClassResolvers;
import io.netty.handler.codec.serialization.ObjectDecoder;
import io.netty.handler.codec.serialization.ObjectEncoder;
import io.netty.handler.ssl.SslContext;
import io.netty.handler.ssl.SslContextBuilder;
import io.netty.handler.ssl.util.InsecureTrustManagerFactory;

/**
 * @author zhengmo
 */
public class Client implements Runnable {
    static final boolean SSL = System.getProperty("ssl") != null;
    static final String HOST = System.getProperty("host", "127.0.0.1");
    static final int PORT = Integer.parseInt(System.getProperty("port", "8089"));
    public static void start() {
        new Thread(new Client()).start();
    }
    public void run() {
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            final SslContext sslCtx;
            if (SSL) { //ssl 连接
                sslCtx = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).build();
                //sslCtx = null;
            } else {
                sslCtx = null;
            }
            Bootstrap b = new Bootstrap();
            b.group(group).channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true).handler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel ch) throws Exception {
                    ChannelPipeline p = ch.pipeline();
                    if (sslCtx != null) {
                        p.addLast(sslCtx.newHandler(ch.alloc()));
                    }
                    p.addLast(new ObjectEncoder(), new ObjectDecoder(ClassResolvers.cacheDisabled(null)), new HelloWorldClientHandler());
                }
            });
            ChannelFuture f = b.connect(HOST, PORT).sync();
            System.out.println("client started...");
            f.channel().closeFuture().sync();
            System.out.println("客户端退出了");
        } catch (Exception e) {
            System.out.println("客户端异常:");
            e.printStackTrace();
            group.shutdownGracefully();
        }
    }
}
